dojo.provide("dojoscratch.PathCommand");

dojo.require("dojoscratch.AbstractCommand");
dojo.require("dojoscratch.DotCommand");

dojo.declare("dojoscratch.PathCommand", dojoscratch.AbstractCommand, {

	constructor : function(boardElement) {
		this._minimalRadius = 2;
	},
	_init : function() {
		this._points = [];
		this._started = false;
	},
	start : function(x, y) {
		this._started = true;
		this._nextPoint(x - this._boardElement.offsetLeft, y
				- this._boardElement.offsetTop);
	},
	doing : function(x, y) {
		if (this._started) {
			this._nextPoint(x - this._boardElement.offsetLeft, y
					- this._boardElement.offsetTop);
		}
	},
	end : function(x, y) {
		if (this._started) {
			this._nextPoint(x - this._boardElement.offsetLeft, y
					- this._boardElement.offsetTop);
			this._command();
			this._init();

		}
	},
	_nextPoint : function(x, y) {
		var pointsCount = this._points.length;
		if (pointsCount > 0) {
			var last = this._points[pointsCount - 1];
			if (Math.abs(last.x - x) <= this._minimalRadius
					|| Math.abs(last.y - y) <= this._minimalRadius) {
				return;
			}
		}
		this._points[pointsCount] = {
			"x" : x,
			"y" : y
		};
		
		this._showPreview(x, y);
	},
	_showPreview: function(x, y) {
		//add offest
		x += this._boardElement.offsetLeft;
		y += this._boardElement.offsetTop;

		var dot = new dojoscratch.DotCommand(this._boardElement);
		dot.start(x, y);
		dot.end(x, y);
	},
	_command : function() {
		var path = "M " + this._points[0].x + " " + this._points[0].y;
		for (i = 1; i < this._points.length; i ++) {
			path += " L " + this._points[i].x + " " + this._points[i].y;
		}
		var path = {
			"type" : "path",
			"path" : path
		};
		var stroke = {
			colors : "black",
			width : 2
		};

		this._createScratch(path, null, stroke);
	}
});